package com.jy.modules.cims.common.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmCostPlanService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.creditright.service.PlanService;
import com.jy.modules.cims.data.common.dto.TCMmCostPlanDTO;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;

/**
 * @classname: TCMmCostPlanController
 * @description: 定义 结算计划 控制层
 * @author: zhiqiang
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmCostPlan")
public class TCMmCostPlanController extends CimsBaseController {
	private static final Logger logger = LoggerFactory.getLogger(TCMmCostPlanController.class);

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCostPlanService")
	private TCMmCostPlanService service;

	@Autowired
	@Qualifier("com.jy.modules.cims.creditright.service.PlanService")
	private PlanService planService;

	/**
	 * 通过 Controller 请求 跳转 进入至相关 页面
	 */
	@RequestMapping(value = "/prepareExecute/{operate}")
	public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
		ModelAndView model = new ModelAndView();

		if ("toQueryPage".equals(operate)) {// 跳转至 查询页面
			model.setViewName("cims/creditDeal/queryTCMmCostPlan");
		} else if ("toAdd".equals(operate)) { // 跳转至 新增页面
			model.setViewName("cims/creditDeal/addTCMmCostPlan");
		} else if ("toUpdate".equals(operate)) {// 跳转至 修改页面
			String id = this.getParameterString("id");
			model = this.queryOneDTO(id);
			model.setViewName("cims/creditDeal/updateTCMmCostPlan");
		} else if ("toView".equals(operate)) {// 跳转至 查看页面
			String id = this.getParameterString("id");
			model = this.queryOneDTO(id);
			model.setViewName("cims/creditDeal/viewTCMmCostPlan");
		}

		return model;
	}

	/**
	 * @author zhiqiang
	 * @description:查询分页列表
	 * @date 2015-01-07 16:21:49
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryListTCMmCostPlan")
	@ResponseBody
	public DataMsg queryListTCMmCostPlan(HttpServletRequest request, TCMmCostPlanDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmCostPlanDTO> list = service.searchTCMmCostPlanByPaging(params.getSearchParams());

		dataMsg.setData(list);
		dataMsg.setTotalRows(pageInfo.getTotalCount());
		return dataMsg;
	}

	/**
	 * @author zhiqiang
	 * @description:新增
	 * @date 2015-01-07 16:21:49
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/insertTCMmCostPlan")
	@ResponseBody
	public DataMsg insertTCMmCostPlan(HttpServletRequest request, TCMmCostPlanDTO dto, @ModelAttribute DataMsg dataMsg) {
		try {
			dto = (TCMmCostPlanDTO) super.initDto(dto);

			service.insertTCMmCostPlan(dto);

			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg("新增成功");
			dataMsg.setData(this.makeJSONData(dto.getId()));
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法insertSysResource异常：", e);
		}
		return dataMsg;
	}

	/**
	 * @author zhiqiang
	 * @description:编辑
	 * @date 2015-01-07 16:21:49
	 * @param request
	 * @param dto
	 * @param pageData
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/updateTCMmCostPlan")
	@ResponseBody
	public DataMsg updateTCMmCostPlan(HttpServletRequest request, TCMmCostPlanDTO dto, @ModelAttribute DataMsg dataMsg) {
		try {
			dto = (TCMmCostPlanDTO) super.initDto(dto);

			service.updateTCMmCostPlan(dto);

			dataMsg = super.initDataMsg(dataMsg);
			dataMsg.setMsg("修改成功");
			dataMsg.setStatus("ok");
			dataMsg.setData(this.makeJSONData(dto.getId()));
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法updateSysResource异常：", e);
		}
		return dataMsg;
	}

	/**
	 * @author zhiqiang
	 * @description:删除
	 * @date 2015-01-07 16:21:49
	 * @param request
	 * @param pageData
	 * @return
	 * @throws
	 */
	@RequestMapping(value = "/deleteTCMmCostPlan")
	@ResponseBody
	public DataMsg deleteTCMmCostPlan(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {

		BaseDTO dto = super.initDto(null);
		String ids = (String) this.getParameter("ids");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		try {
			service.deleteTCMmCostPlanByPrimaryKey(dto, ids);
			dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);

		}

		return dataMsg;
	}

	/**
	 * @author zhiqiang
	 * @description:通过主键查询 其明细信息
	 * @date 2015-01-07 16:21:49
	 * @param id
	 * @return
	 */
	private ModelAndView queryOneDTO(String id) throws AbaboonException {
		ModelAndView model = new ModelAndView();
		try {
			TCMmCostPlanDTO dto = service.queryTCMmCostPlanByPrimaryKey(id);
			// 将信息放入 model 以便于传至页面 使用
			model.addObject("dto", dto);
		} catch (Exception e) {
			throw new AbaboonException("执行queryOneDTO异常：", e);
		}
		return model;
	}

	@RequestMapping(value = "/restCostPlanByTransferId")
	@ResponseBody
	public DataMsg restCostPlanByTransferId(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		String transferId = (String) this.getParameter("transferId");// 格式:
																		// 1,2,3
		try {
			if (SimpleStringUtils.hasText(transferId)) {
				planService.doRestPlanByTransferId(transferId);
				dataMsg.setMsg("生成成功！");
				dataMsg.setStatus("yes");
			} else {
				dataMsg.setMsg("债权转让编号不能为空！");
				dataMsg.setStatus("no");
			}
		} catch (Exception e) {
			dataMsg.setMsg("执行异常:" + ExceptionUtils.getStackTraceAsString(e));
			dataMsg.setStatus("no");
			logger.error("执行方法restCostPlanByTransferId异常：", e);
		}
		return dataMsg;
	}

	@RequestMapping(value = "/buildPlan")
	@ResponseBody
	public DataMsg buildPlan(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		try {
			List<String> errorMessageList = planService.buildPlan();
			if (CollectionsUtils.isEmpty(errorMessageList)) {
				dataMsg.setMsg("还款计划和结算计划生成完毕！请查询");
				dataMsg.setStatus("yes");
			} else {
				String message = CollectionsUtils.convertToString(errorMessageList, ";\n");
				dataMsg.failed(message);
				dataMsg.setStatus("no");
			}
		} catch (Exception e) {
			dataMsg.setMsg("执行异常:" + e.getMessage());
			dataMsg.setStatus("no");
			logger.error("执行方法buildPlan异常：", e);
		}
		return dataMsg;
	}

	/**
	 * 导出结算计划列表
	 * 
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 */
	@RequestMapping(value = "/exportCostPlan")
	@ResponseBody
	public void exportCostPlan(HttpServletRequest request, HttpServletResponse response, TCMmCostPlanDTO dto, @ModelAttribute DataMsg dataMsg) {

		String fileName = "结算计划列表";
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);

		ExportAndImport<TCMmCostPlanDTO> exportAndImport = new ExportAndImport<TCMmCostPlanDTO>();
		String columnCode = CimsConstant.COST_PLAN_FILE_EXPORT_CODE;
		String columnName = CimsConstant.COST_PLAN_FILE_EXPORT_NAME;
		HSSFWorkbook workbook;
		List<TCMmCostPlanDTO> list = null;
		try {
			int listSize = service.searchTCMmCostPlanSum(searchParams);
			if (listSize > 10000) {
				fileName = "导出失败!(数据限制小于等于10000条)";
			} else {
				list = service.searchTCMmCostPlan(searchParams);
				for (TCMmCostPlanDTO costPlanDTO : list) {
					if (costPlanDTO.getPlanStatus() == null || costPlanDTO.getPlanStatus().equals("")) {
						costPlanDTO.setPlanStatus("未结算");
					} else if (costPlanDTO.getPlanStatus().equals("01")) {
						costPlanDTO.setPlanStatus("已结算");
					}
				}
			}

			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
			write(workbook, fileName, response);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.INGURL_FILE + e);
		}
	}

	/**
	 * 页面输出
	 * 
	 * @param workbook
	 * @param fileName
	 * @param response
	 * @throws IOException
	 */
	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

		try {

			response.setContentType("application/vnd.ms-excel");
			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			workbook.write(response.getOutputStream());
			response.getOutputStream().flush();
		} catch (Exception e) {
			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
		} finally {
			response.getOutputStream().close();
		}
	}
}
